package cn.lysj.framework.app.controller;

import cn.lysj.framework.app.base.AppWaiMaiContent;
import cn.lysj.framework.common.exception.MyException;
import cn.lysj.framework.common.utils.json.JacksonUtil;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.websocket.IncidentType;
import cn.lysj.framework.common.utils.websocket.WebSocketServerToStore;
import cn.lysj.framework.elm.domain.ElmConfig;
import cn.lysj.framework.elm.domain.ElmOrder;
import cn.lysj.framework.elm.domain.ElmRequest;
import cn.lysj.framework.elm.elmenum.ElmOrderStatus;
import cn.lysj.framework.elm.elmenum.ElmOrderWay;
import eleme.openapi.sdk.api.entity.other.OMessage;
import eleme.openapi.sdk.api.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 9:31 2019/1/21
 * @ Description:
 **/
@RestController
@RequestMapping("/app/elm")
@Slf4j
public class AppElmController extends AppWaiMaiContent {


    /*
     * @author drj
     * @date 2019-01-21 10:25
     * @Description :获取授权码
     */
    @GetMapping("/get_auth_code")
    public void getAuthCode(HttpServletRequest request) throws IOException {
        String authCode = request.getParameter("code");
        if (!ParamUtil.isBlank(authCode)) {
            elemeContent.authcode = authCode;
            elemeContent.cash_token = elemeContent.client.getTokenByCode(authCode, elemeContent.redirect_url);
            response.getWriter().write("<br>code:" + elemeContent.authcode);
            response.getWriter().flush();
            response.getWriter().close();
        }
    }


    @PostMapping("/get_order")
    public String getOrder(@RequestBody OMessage oMessage) throws ServiceException {
        log.info("进入接单");
        if (null == oMessage) {
            return null;
        }
        //推送消息去重处理
        int count = elemeContent.elemeRequestService.getRepository()
                .countByRequestId(oMessage.getRequestId());
        if (count >= 1) {
            return null;
        }
        //将message返回的信息转成map
        Map<String, Object> map = JacksonUtil.toObjectMap(oMessage.getMessage());
        //根据appid查询平台对应门店的配置信息
        ElmConfig elmConfig = elemeContent.elmConfigService.getRepository().findByAppId(String.valueOf(oMessage.getAppId()));
        //获取门店id
        String storeId = elmConfig.getStoreId();
        //获取订单编号
        String orderNumber = String.valueOf(map.get("id"));
        ElmOrder elmOrder = new ElmOrder();
        //若请求消息类型为10,用户下单
        if (ElmOrderStatus.EFFECT.getCode().equals(oMessage.getType())) {
            //语音提醒
            WebSocketServerToStore.sendDataToMorePeopleMap(IncidentType.SEND_FOOD_ORDER_RADIO, "", elmConfig.getStoreId(), true);
            //将饿了么平台的订单信息拷贝到平台订单中
            elmOrder = elemeContent.elmOrderService.getElmOrder(orderNumber, storeId);
            //如果设置的是自动动接单,
            if (ElmOrderWay.AUTOORDER.getCode().equals(elmConfig.getOrderWay())) {
                elemeContent.elmOrderService.manualOrder(elmOrder.getId());
            }
        }
        //若请求消息类型为30,用户申请退款
        if (ElmOrderStatus.APPLYING.getCode().equals(oMessage.getType())) {
            WebSocketServerToStore.sendDataToMorePeopleMap(IncidentType.SEND_REFUND_RADIO, "", elmConfig.getStoreId(), true);
            elmOrder = elemeContent.elmOrderService.getRepository().findByOrderNumber(String.valueOf(map.get("orderId")));
            if (null == elmOrder) {
                log.info("退单传入单号为:" + String.valueOf(map.get("orderId")));
                throw new MyException("未知错误");
            }
            elmOrder.setOrderStatus(ElmOrderStatus.APPLYING.getCode());
            elemeContent.elmOrderService.save(elmOrder);
        }
        //创建推送消息
        ElmRequest elmRequest = new ElmRequest();
        elmRequest.setRequestId(oMessage.getRequestId());
        elemeContent.elemeRequestService.save(elmRequest);
        return null;
    }

    /*
     * @author drj
     * @date 2019-02-26 15:15
     * @Description: 用于处理消息推送
     */
//    @GetMapping("/get_order")
//    public String getOrder() {
//        Map<String, Object> map = new HashMap<>();
//        map.put("message", "ok");
//        return JacksonUtil.toJson(map);
//    }


}
